package csc.daonjpa.java.controller;
import javax.servlet.http.HttpServletRequest;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import share.Constant;
import csc.daonjpa.java.domain.Customer;
import csc.daonjpa.java.domain.JSONResponse;
import csc.daonjpa.java.service.CustomerService;
import csc.daonjpa.java.service.LogService;

@Controller
public class CustomerController {

	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
    ReCaptchaImpl reCaptcha;
	/**
	 * @return the customerService
	 */
	public CustomerService getCustomerService() {
		return customerService;
	}

	/**
	 * @param customerService the customerService to set
	 */
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}
	
	@RequestMapping(value = "/loginCustomer")
	public String doLoginCustomer(HttpServletRequest request, Model model,
			@RequestParam("recaptcha_challenge_field") String challangeField, 
	        @RequestParam("recaptcha_response_field") String responseField) {
		// Read account info from request and save into Account object
		String loginId = request.getParameter(Constant.PARAM_LOGINID);
		String password = request.getParameter(Constant.PARAM_PASSWORD);
		String forward = Constant.STR_EMPTY;
		int failedCount;
		
		String remoteAddress = request.getRemoteAddr();
        ReCaptchaResponse reCaptchaResponse = this.reCaptcha.checkAnswer(remoteAddress, challangeField, responseField);
 
			Customer customerExistence = customerService.getCustomerByLoginId(loginId);		
			Customer customer = customerService.checkLogin(loginId, password);	
			
			//check username field fulfilled or not AND customer existence
			if ((loginId != null) && (customerExistence!=null)) {
				//check pass & status
				failedCount = customerExistence.getFailedCount();
					//locked
					if(failedCount>=3){
						JSONResponse response = new JSONResponse();
						response.setSuccess(false);
						response.setMessage("Your account is Locked, please contact administrator!");
						model.addAttribute(Constant.MODEL_OBJ_LOGIN_RESULT, response);
						logService.createLog("Login failed, locked account", customer);
						forward = Constant.VIEW_LOGIN;
					}
					
					//right pass and acc active
					else if ((customer != null) && (failedCount<3)) {
						if(reCaptchaResponse.isValid()){
							//login success						
							request.getSession().setAttribute(Constant.SESSION_ATR_CUSTOMER_ID, customer.getId());
							request.getSession().setAttribute(Constant.SESSION_ATR_IS_CUSTOMER, new Boolean(true));
							customerService.resetFailedCount(customer.getId());
							model.addAttribute(Constant.MODEL_OBJ_CUSTOMER, customer);
							forward = Constant.VIEW_CUSTOMER_INFO;
							logService.createLog("Login successful to system", customer);						
						
						}//captcha valid
						
						else{//captcha invalid
							JSONResponse response = new JSONResponse();
							response.setSuccess(false);
							response.setMessage("Invalid captcha please try again!");
							model.addAttribute(Constant.MODEL_OBJ_LOGIN_RESULT, response);
							forward = Constant.VIEW_LOGIN;
						}
					}		
					
					//wrong pass
					else{
						customerService.updateFailedCount(customerExistence);
						JSONResponse response = new JSONResponse();
						response.setSuccess(false);
						int remainInt = 2-failedCount;
						String remain = Integer.toString(remainInt);
						response.setMessage("Login failed: wrong username or password! You have  "+ remain +"  time(s) remaining!");
						model.addAttribute(Constant.MODEL_OBJ_LOGIN_RESULT, response);						
						forward = Constant.VIEW_LOGIN;
					}						
				}
		
			else{//username field unfulfilled or customer NI
				JSONResponse response = new JSONResponse();
				response.setSuccess(false);
				response.setMessage("Login failed: wrong username or password!");
				customerService.updateFailedCount(customerExistence);
				model.addAttribute(Constant.MODEL_OBJ_LOGIN_RESULT, response);						
				forward = Constant.VIEW_LOGIN;
			}//end if-check username field fulfilled or not AND customer existence
		
        	return forward;
		}
        	
      
	
	@RequestMapping(value = "/changePassword")
	public String changePassword(HttpServletRequest request, Model model) {
		toCustomerInfo(model, request);
		return Constant.VIEW_CHANGE_PASSWORD;
	}
	
	@RequestMapping(value ="/doChangePassword")
	public @ResponseBody JSONResponse doChangePassword(HttpServletRequest request, Model model){
		Long customerId = (Long) request.getSession().getAttribute(Constant.SESSION_ATR_CUSTOMER_ID);
		String oldPassword = request.getParameter(Constant.PARAM_OLDPASSWORD);
		String newPassword = request.getParameter(Constant.PARAM_NEW_PASSWORD);
		JSONResponse response = new JSONResponse();
		boolean isUpdatePasswordSuccess = customerService.updatePassWord(customerId, oldPassword, newPassword);
		
		if(isUpdatePasswordSuccess == true){
			response.setSuccess(true);
			logService.createLog("Change password", customerId);
		}
		else{
			System.out.println("retype old password");
			response.setSuccess(false);
			response.setMessage("Invalid old password");
		}
		return response;
	}
	
	@RequestMapping(value = {"customerInfo", "home", "/"})
	public String toCustomerInfo(Model model, HttpServletRequest request) {
		Long customerId = (Long) request.getSession().getAttribute(Constant.SESSION_ATR_CUSTOMER_ID);
		model.addAttribute(Constant.MODEL_OBJ_CUSTOMER, customerService.getCustomer(customerId));
		return Constant.VIEW_CUSTOMER_INFO;
	}
}
